package com.yixin.hospital.controller;

import cn.hutool.core.bean.BeanUtil;
import com.yixin.hospital.common.ApiResult;
import com.yixin.hospital.common.Constant;
import com.yixin.hospital.entity.domain.Card;
import com.yixin.hospital.entity.dto.req.card.CardAddReqDTO;
import com.yixin.hospital.entity.dto.req.card.CardEditReqDTO;
import com.yixin.hospital.entity.vo.CardVo;
import com.yixin.hospital.entity.vo.GoDownDrugVo;
import com.yixin.hospital.service.CardService;
import com.yixin.hospital.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/card")
@Api(value = "卡管理", tags = "卡管理")
@Slf4j
public class CardController {

    @Resource
    CardService cardService;

    @GetMapping("/list")
    @ApiOperation(value = "卡列表")
    public ApiResult<List<CardVo>> list() {
        List<Card> list = cardService.list();
        List<CardVo> cardVos = BeanUtil.copyToList(list, CardVo.class);
        for (CardVo cardVo : cardVos) {
            cardVo.setCardId(cardVo.getId());
            cardVo.setCardName(cardVo.getName());
        }
        return ApiResult.success(cardVos);
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加卡")
    public ApiResult<?> add(@Valid @RequestBody CardAddReqDTO cardAddReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        Card card = new Card();
        BeanUtils.copyProperties(cardAddReqDTO, card);
        card.setCreatedBy(userName);
        card.setUpdatedBy(userName);
        cardService.save(card);
        return ApiResult.success();
    }

    @PutMapping("/edit")
    @ApiOperation(value = "编辑卡")
    public ApiResult<?> edit(@Valid @RequestBody CardEditReqDTO CardEditReqDTO, HttpServletRequest request) {
        String userName = JwtUtil.getName(request.getHeader(Constant.AUTHORIZATION));
        Card card = new Card();
        BeanUtils.copyProperties(CardEditReqDTO, card);
        card.setUpdatedBy(userName);
        log.info("card:{}", card);
        cardService.updateById(card);
        return ApiResult.success();
    }

    @DeleteMapping("/remove/{id}")
    @ApiOperation(value = "删除卡")
    public ApiResult<?> remove(@PathVariable int id) {
        cardService.removeById(id);
        return ApiResult.success();
    }

}
